import json
import os
from datetime import datetime

class VideoHistory:
    def __init__(self):
        self.history_file = 'video_history.json'
        self.history = self.load_history()
    
    def load_history(self):
        if os.path.exists(self.history_file):
            try:
                with open(self.history_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                return []
        return []
    
    def save_history(self):
        with open(self.history_file, 'w', encoding='utf-8') as f:
            json.dump(self.history, f, ensure_ascii=False, indent=4)
    
    def add_video(self, video_path):
        # 获取视频文件名
        video_name = os.path.basename(video_path)
        
        # 创建历史记录条目
        history_entry = {
            'video_name': video_name,
            'video_path': video_path,
            'last_played': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 检查是否已存在该视频的记录
        for entry in self.history:
            if entry['video_path'] == video_path:
                self.history.remove(entry)
                break
        
        # 将新记录添加到列表开头
        self.history.insert(0, history_entry)
        
        # 限制历史记录数量为最近20个
        self.history = self.history[:20]
        
        # 保存历史记录
        self.save_history()
    
    def get_recent_videos(self, limit=10):
        return self.history[:limit]